﻿

import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { downloadfun, isImageFile, IgetDeptList, DeleteModuleFile, queryURLParams, dealTime, getBrowserInfo, getRecentYears, CONSTPARAMSDATA } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const data = reactive({
        pdfOpen: false,
        pdfurl: "",
        messageTest: "",
        proxy: "",
        popShow: false,
        imgUrl: "",
        previewShow: false,
        settingList: [
        ],
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        FactoryAreaList: [
            {
                label: '浦东',
                value:1
            },
            {
                label: '大场',
                value: 2
            },
        ],
        yearlist: [],
        itemRender: (data) => {
            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => methods.btnDelete(data)

            }, { default: () => [deleteBtn] })
            var btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url) ? previewBtn : null,
                    downloadBtn,
                    params.urlinfo.value.type == 9 ? null : FDBtn
                ]
            })
            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        typelist: CONSTPARAMSDATA.typelist,
        uploadLock: false,
        formData: {
            SupplyName: null,
            LevelId: null,
            DepartmentId:null
        },
        deptList:[],
        rules: {
            //SupplyName: [{ required: true, message: '请填写物资内容', trigger: 'change' }],
        },
        urlinfo: {},


    })
    let params = toRefs(data)
    const methods = {
        setVisible: (value) => {
            params.previewShow.value = value;
        },
        getDeptList: () => {
            return new Promise(async (resolve, rej) => {
                params.deptList.value = await IgetDeptList(Request)
                //if (params.deptList.value) {
                //    resolve(1)
                //}
            })
        },
        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url

                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            downloadfun(name, url)

        },
        btnDelete: (e) => {

            const { FileId } = e.file
            if (FileId) {
                params.uploadLock.value = true
                DeleteModuleFile(Request, FileId).then(res => {
                    params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(e => e.FileId != FileId)
                    params.messageTest.value.success(res.Msg);
                }).finally(() => {
                    params.uploadLock.value = false
                })
            }
        },
        addConfig: () => {
            let obj = {
                FactoryAreaId: null,
                Name: null,
                Quantity: null,
                Unit: null,
                Responsible: null,
                Contact: null,
                Place: null,
                ValidDate: null
            }
            params.settingList.value.push(obj)
        },
        handleDownloadTemplate: () => {
            params.uploadLock.value = true
            downloadfun('导入应急物资模板', '../../File/Templete/EmergencySupplies/导入应急物资模板.xls').then(() => {


            }).finally(() => {

                params.uploadLock.value = false
            })
        },
        handleChange: (info) => {
            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('file', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: `/EmergencyPlan/ImportEmergencySuppliesItem`,
                    method: 'post',
                    data: formData
                }).then(res => {
                    params.settingList.value = res.Data.map(e => {
                        e.ValidDate = dayjs(dealTime(e.ValidDate))
                        return e
                    })
                    params.uploadLock.value = false


                })

            }
        },
        delConfig: (index) => {
            params.settingList.value=params.settingList.value.filter((_e, i)=>i!=index)
        },
        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },
        IGetEmergencySuppliesDetail: () => {
            return new Promise((resolve, rej) => {
                params.uploadLock.value=true
                Request({
                    url: "/EmergencyPlan/GetEmergencySuppliesDetail",
                    method: 'post',
                    data: {
                        Id: params.urlinfo.value.id
                    }
                }).then(res => {

                    params.formData.value = res.Data
                    params.formData.value.user = `${res.Data.CreateUserName}(${res.Data.UpdateUser})`
                    params.formData.value.time = dealTime(res.Data.UpdateTime, 'YYYY-MM-DD HH:mm')
                    params.settingList.value = res.Data.Items.map(e => {
                        e.ValidDate = dayjs(dealTime(e.ValidDate))
                        return e 
                    })
                    params.uploadLock.value = false
                    resolve()

                })
            })
       
        },


        handleAddData: (data) => {
            params.uploadLock.value = true
            if (params.urlinfo.value.type == 1) {
                Request({
                    url: "/EmergencyPlan/EditEmergencySupplies",
                    method: 'post',
                    data: data
                }).then(res => {
                    if (res.Code == 100) {
                        params.messageTest.value.info(res.Msg)
                        setTimeout(() => {
                            methods.onBack()
                        }, 1000)

                    }
                }).finally(() => {
                    params.uploadLock.value = false
                })
            } else {
                Request({
                    url: "/EmergencyPlan/AddEmergencySupplies",
                    method: 'post',
                    data: data
                }).then(res => {
                    if (res.Code == 100) {
                        params.messageTest.value.info(res.Msg)
                        setTimeout(() => {
                            methods.onBack()
                        }, 1000)

                    }
                }).finally(() => {
                    params.uploadLock.value = false
                })
            }

          


        },

        onSubmit(Status) {
            let obj = {
                model: {
                    ...params.formData.value,
                    Status,

                    Id: params.urlinfo.value.id
                },
                items: params.settingList.value
            }
            if (Status == 0) {
                methods.handleAddData(obj)
            } else {
                params.proxy.value.$refs.FormRule.validate().then(() => {
                    methods.handleAddData(obj)
                }).catch((res) => {

                    params.messageTest.value.info(res.errorFields[0].errors[0] || res);
                })
            }
         
        },

        onBack: () => {
            window.location.href ='/EmergencyManagement/EMList'
        },


        init: () => {
            getBrowserInfo().catch(err => { console.log(err) })
            params.urlinfo.value = queryURLParams()
            params.yearlist.value = getRecentYears()
            params.formData.value.Years = dayjs().format('YYYY')

            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                Storage.set('token', res.Data,true)
                methods.getDeptList()
                if (params.urlinfo.value.type) {
                    methods.IGetEmergencySuppliesDetail()
                } else {
                    params.formData.value.user = `${info.UserName}(${info.UserNo})`
                    params.formData.value.time = dayjs().format('YYYY-MM-DD HH:mm')
                    params.formData.value.DepartmentId = info.DepartmentId
                    params.formData.value.LevelId = params.urlinfo.value.l
                }
           
       
              
            })

            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });

        },

    }
    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width= "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },


        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>

  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
          <a-button  :loading="uploadLock" v-if="urlinfo.type!=9">保存</a-button>
  </a-popconfirm>
  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
          <a-button  :loading="uploadLock" v-if="urlinfo.type!=9" type="primary">发布</a-button>
  </a-popconfirm>
                       
              
                        <a-button v-on:click="onBack" :loading="uploadLock">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition